package com.ias.agdis_r.util.network;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.ias.agdis_r.util.S;

/**
 * WIFI工具类
 * @author zhangsc
 *
 */
public class WifiUtil {

	 public final static String TAG_BSSID = "BSSID";
	 public final static String TAG_SSID = "SSID";
	 public final static String TAG_TYPE = "TYPE";
	 public final static String TAG_LEVEL = "LEVEL";
	 public final static String TAG_STATE = "STATE";
	 public final static String TAG_SAVE = "SAVE";
	 WifiManager wifiManager;  
   
	 //定义几种加密方式，一种是WEP，一种是WPA，还有没有密码的情况  
	 public enum WifiCipherType  
	 {  
	     WIFICIPHER_WEP,WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID  
	 }  

	 public WifiUtil(Context context)  
	 {  
		  wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
	 }  
	  
	/**
	 * 获取WIFI的状态
	 */
	public boolean isWifiEnabled()
	{
		return wifiManager.isWifiEnabled();
	}
	
	/**
	 * 打开WIFI
	 * @return
	 */
	public boolean openWifi()  
	{  
	     boolean bRet = true;  
	     if (!wifiManager.isWifiEnabled())  
	     {  
	         bRet = wifiManager.setWifiEnabled(true);    
	     }  
	     return bRet;  
	}  
	
	/**
	 * 关闭WIFI
	 * @return
	 */
	public boolean closeWifi()  
	{  
	     boolean bRet = true;  
	     if (wifiManager.isWifiEnabled())  
	     {  
	         bRet = wifiManager.setWifiEnabled(false);    
	     }  
	     return bRet;  
	}  
	
	/**
	 * 获取WIFI类型
	 * @return
	 */
	public WifiCipherType getType(String type,String password) {  
		
		if(S.isEmpty(password)) {
		    return WifiCipherType.WIFICIPHER_NOPASS;
		 } else if (type.contains("WEP")) {  
		    return WifiCipherType.WIFICIPHER_WEP;  
		 } else if (type.contains("WPA")) {  
		    return WifiCipherType.WIFICIPHER_WPA;  
		 } else{  
		    return WifiCipherType.WIFICIPHER_INVALID;  
		 }  
	 }  
	 
	/**
	 * 连接WIFI
	 * @param ssid
	 * @param password
	 * @param typeList
	 * @return
	 */
	//提供一个外部接口，传入要连接的无线网  
	public boolean connect(String ssid, String password,String typeList)  
	{  
	   if(!this.openWifi())  
	   {  
	       return false;  
	   }  
	//开启wifi功能需要一段时间(一般需要1-3秒左右)，所以要等到wifi  
	//状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句  
	   while(wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING )  
	   {  
	      try{  
	      //为了避免程序一直while循环，让它睡个100毫秒在检测……  
	           Thread.currentThread();  
	           Thread.sleep(100);  
	      }  
	      catch(InterruptedException ie){  
	    	  
	      }  
	    }  
	   
	    WifiCipherType type = getType(typeList,password);
	    WifiConfiguration wifiConfig = this.createWifiInfo(ssid, password, type);  
	        
	    if(wifiConfig == null)  
	    {  
	         return false;  
	    }  
	    WifiConfiguration tempConfig = this.getWifiConfig(ssid);  
	          
	    if(tempConfig != null)  
	    {  
	       wifiManager.removeNetwork(tempConfig.networkId);  
	    }     
	    int netID = wifiManager.addNetwork(wifiConfig);  
	    boolean bRet = wifiManager.enableNetwork(netID, true);    
	    return bRet;  
	}  
	      
	/**
	 * 断开WIFI
	 * @return
	 */
	public boolean discon()
	{
	   WifiInfo connectInfo =  wifiManager.getConnectionInfo();
	   wifiManager.disableNetwork(connectInfo.getNetworkId());
	   return true;
	}
	
	/**
	 * 查看以前是否也配置过这个网络  
	 * @param SSID
	 * @return
	 */  
	private WifiConfiguration getWifiConfig(String SSID)  
	{  
	   List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();  
	   for (WifiConfiguration existingConfig : existingConfigs)   
	   {  
	      if (existingConfig!=null&&existingConfig.SSID.equals("\""+SSID+"\""))  
	      {  
	          return existingConfig;  
	      }  
	    }  
	    return null;   
	}  
	
	/**
	 * 创建WIFI连接
	 * @param SSID
	 * @param Password
	 * @param Type
	 * @return
	 */
	private WifiConfiguration createWifiInfo(String SSID, String Password, WifiCipherType Type)  
	{  
		WifiConfiguration config = new WifiConfiguration();    
		config.allowedAuthAlgorithms.clear();  
		config.allowedGroupCiphers.clear();  
		config.allowedKeyManagement.clear();  
		config.allowedPairwiseCiphers.clear();  
		config.allowedProtocols.clear();  
		config.SSID = "\"" + SSID + "\"";    
	    if(Type == WifiCipherType.WIFICIPHER_NOPASS)  
	    {  
	        config.wepKeys[0] = "";  
	        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);  
	        config.wepTxKeyIndex = 0;  
	    }  
	    else if(Type == WifiCipherType.WIFICIPHER_WEP)  
	    {  
	       config.preSharedKey = "\""+Password+"\"";   
	       config.hiddenSSID = true;    
	       config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);  
	       config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);  
	       config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);  
	       config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);  
	       config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);  
	       config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);  
	       config.wepTxKeyIndex = 0;  
	     }  
	     else if(Type == WifiCipherType.WIFICIPHER_WPA)  
	     {  
	        config.preSharedKey = "\""+Password+"\"";   
	        config.hiddenSSID = true;     
	        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);     
	        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);                           
	        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);                           
	        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);                         
	        config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);  
	        config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);  
	        config.status = WifiConfiguration.Status.ENABLED;    
	     }  
	     else  
	     {  
	        return null;  
	     }  
	     return config;  
	}
	
	/**
	 * 去除同名WIFI
	 * 
	 * @param 需要去除同名的列表
	 * @return 返回不包含同命的列表
	 */
	public List<ScanResult> noSameName(List<ScanResult> oldSr)
	{
	      List<ScanResult> newSr = new ArrayList<ScanResult>();
	      for (ScanResult result : oldSr)
	     {
	          if (!S.isEmpty(result.BSSID) && !containName(newSr, result.BSSID))
	               newSr.add(result);
	     }
	     return newSr;
	}
	
	 /**
	  * 判断一个扫描结果中，是否包含了某个名称的WIFI
	  * 
	  * @param sr
	  *            扫描结果
	  * @param name
	  *            要查询的名称
	  * @return 返回true表示包含了该名称的WIFI，返回false表示不包含
	  */
	 public boolean containName(List<ScanResult> sr, String name)
	 {
	       for (ScanResult result : sr)
	       {
	             if (!S.isEmpty(result.BSSID) && result.BSSID.equals(name))
	                   return true;
	       }
	       return false;
	 }
	/**
	 * 获取WIFI列表
	 */
	public List<HashMap<String,Object>> getWifiList()
	{
		WifiInfo connectInfo = wifiManager.getConnectionInfo();
		List<HashMap<String,Object>> wifiList = new ArrayList<HashMap<String,Object>>();
		String conBSSID = "";
		if(connectInfo!=null)
		{
			conBSSID = connectInfo.getBSSID();
		}
		if(wifiManager.isWifiEnabled())
		{		
			List<ScanResult>  scanList   = wifiManager.getScanResults();
			scanList = noSameName(scanList);
			for(int i=0;i<scanList.size();i++)
			{
				ScanResult scanResult = scanList.get(i);			  
				HashMap<String,Object> wifiMap = new HashMap<String,Object>();
				wifiMap.put(TAG_BSSID,scanResult.BSSID);
				wifiMap.put(TAG_SSID, scanResult.SSID);
				wifiMap.put(TAG_TYPE, scanResult.capabilities);
			    int nSigLevel = WifiManager.calculateSignalLevel(  
	                        scanResult.level, 5); 
				wifiMap.put(TAG_LEVEL, nSigLevel);
				if(scanResult.BSSID.equals(conBSSID))
				{
					wifiMap.put(TAG_STATE,true);
				}
				else
				{
					wifiMap.put(TAG_STATE,false);
				}
				
				if(getWifiConfig(scanResult.SSID)!=null)
				{
					wifiMap.put(TAG_SAVE,true);
				}
				else
				{
					wifiMap.put(TAG_SAVE,false);
				}
				wifiList.add(wifiMap);
			}
		}
		else
		{
//			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,
//					"当前WIFI状态不可用", false);
		}	
		return wifiList;
	}
}
